package proccess

import (
	"context"
	. "gitee.com/youbeiwuhuan/go-xxljob-executor/global"
	"go.uber.org/zap"
	"io/ioutil"
	"os"
	"time"
)

const (
	CLEAN_IDLE_HOURS = 6
)

type JobLogFileCleanProccessor struct {
	logRetentionDays int32
	xxlLogPath       string

	cancel context.CancelFunc
}

func NewJobLogFileCleanProccessor(logRetentionDays int32, logPath string) *JobLogFileCleanProccessor {
	return &JobLogFileCleanProccessor{
		logRetentionDays: logRetentionDays,
		xxlLogPath:       logPath + "/jobhandler",
	}
}

func (t *JobLogFileCleanProccessor) Start() {
	ctx, cancle := context.WithCancel(context.Background())
	t.cancel = cancle

	go func() {

	LOOP_TRIGGER:
		for {
			select {
			case <-ctx.Done():
				Logger.Info(">>>>>stop")
				break LOOP_TRIGGER
			default:
				t.doClean()
				time.Sleep(time.Duration(CLEAN_IDLE_HOURS) * time.Hour)
			}

		}
	}()
}

func (t *JobLogFileCleanProccessor) Stop() {
	t.cancel()
}

func (t *JobLogFileCleanProccessor) doClean() {
	files, err := ioutil.ReadDir(t.xxlLogPath)
	if nil != err {
		Logger.Error("", zap.Any("error", err))
		return
	}

	if nil == files || 0 == len(files) {
		return
	}

	for _, f := range files {
		if !f.IsDir() {
			continue
		}

		dirName := f.Name()

		if "." == dirName || ".." == dirName {
			continue
		}

		Logger.Info("&&&&&&&&&&&&&&&&&" + t.xxlLogPath + "/" + f.Name())

		d, err := time.ParseInLocation("2006-01-02", dirName, time.Local)
		if nil != err {
			os.RemoveAll(t.xxlLogPath + "/" + f.Name())
			continue
		}

		//超过logRetentionDays的删掉
		if time.Now().Sub(d) > time.Duration(t.logRetentionDays)*24*time.Hour {
			Logger.Info("@@@@@" + t.xxlLogPath + "/" + f.Name())
			os.RemoveAll(t.xxlLogPath + "/" + f.Name())
		}

	}

}
